#!/bin/bash

# =================================================================
# FEATURES:
# 1. One-click to start development server
# 2. Multiple browser opening methods (for maximum compatibility)
# 3. Compatible with all Node.js versions
# 4. Multiple fallbacks if one method fails
# =================================================================

echo "===================================="
echo "    Hello Frontend Startup Tool"
echo "===================================="
echo

# Change to script directory
cd "$(dirname "$0")"

# Check dependencies
if [ ! -d "node_modules" ]; then
    echo "[INFO] Dependencies not installed. Installing now..."
    npm install --registry=https://registry.npmmirror.com
    if [ $? -ne 0 ]; then
        echo "[ERROR] Failed to install dependencies."
        echo "Press any key to exit..."
        read -n 1 -s
        exit 1
    fi
    echo "[SUCCESS] Dependencies installed."
    echo
fi

# Create a temporary HTML file that will auto-redirect to our app
cat > redirect.html << 'EOF'
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="0;URL='http://localhost:80/'" />
<title>Redirecting...</title>
</head>
<body>
<p>If you are not redirected automatically, click <a href="http://localhost:80/">here</a>.</p>
<p>If that doesn't work, try <a href="http://localhost:81/">this link instead</a>.</p>
</body>
</html>
EOF

echo "[INFO] Starting development server..."
echo "[INFO] A browser window will open in a moment..."
echo "[INFO] Press Ctrl+C to stop the server when done"
echo

# Method 1: Open the redirect page directly in a new window
open redirect.html

echo "[INFO] Browser windows should open automatically"
echo "[INFO] If browser doesn't open or shows blank page, manually visit:"
echo "[INFO] http://localhost:80/ or http://localhost:81/"
echo

# 设置环境变量并运行vue-cli-service (Mac兼容方式)
export NODE_OPTIONS=--openssl-legacy-provider
./node_modules/.bin/vue-cli-service serve

# Check if the process ended with an error
if [ $? -ne 0 ]; then
    echo
    echo "[ERROR] Server stopped unexpectedly with error code $?"
    echo "[INFO] Please check the error messages above."
fi

# Clean up
if [ -f "redirect.html" ]; then
    rm redirect.html
fi

echo
echo "[INFO] Server has been stopped."
echo "Press any key to exit..."
read -n 1 -s